package leetcode.list;

import java.util.*;

/**
 * 给定一个 没有重复 数字的序列，返回其所有可能的全排列。
 * <p>
 * 示例:
 * <p>
 * 输入: [1,2,3]
 * 输出:
 * [
 * [1,2,3],
 * [1,3,2],
 * [2,1,3],
 * [2,3,1],
 * [3,1,2],
 * [3,2,1]
 * ]
 */
public class Permute {

    private static void dfs(int[] nums, int len, int depth, List<Integer> list, List<List<Integer>> result, boolean[] used) {
        if (depth != len) {
            for (int i = 0; i < len; i++) {
                if (!used[i]) {
                    List<Integer> newList = new ArrayList<>(list);
                    newList.add(nums[i]);

                    boolean[] newUsed = new boolean[len];
                    System.arraycopy(used, 0, newUsed, 0, len);
                    newUsed[i] = true;

                    dfs(nums, len, depth + 1, newList, result, newUsed);
                }
            }
        } else {
            result.add(list);
            return;
        }
    }

    public static List<List<Integer>> permute(int[] nums) {

        if (nums.length == 0) {
            return null;
        }

        List<List<Integer>> result = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        List<Integer> list = new ArrayList<>();
        dfs(nums, nums.length, 0, list, result, used);
        return result;
    }


}
